<template>
  <a-modal
    v-model:visible="dataModel.visible"
    :mask-closable="false"
    :ok-loading="loading"
    :on-before-ok="handleOk"
    @cancel="handleCancel"
  >
    <template #title>
      {{ dataModel.title }}
    </template>
    <div>
      <a-form
        ref="adminModalForm"
        :model="formData"
        :disabled="dataModel.disabled"
        :style="{width:'100%'}">
        <a-form-item
          field="username"
          label="用户名"
          :rules="[{required: true, message:'请输入用户名'}]">
          <a-input v-model="formData.username" placeholder="请输入用户名..." allow-clear />
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import useDataModel from '@/hooks/data-model'
import useLoading from '@/hooks/loading'
import { Operation } from '@/types/global'
import { ref } from 'vue'
import { ValidatedError } from '@arco-design/web-vue/es/form/interface'
import { setUpAdmin } from '@/api/modules/system/tenant'

const formData = ref({
  tenantId: '',
  username: ''
})
const adminModalForm = ref<any>(null)
const { dataModel, openModel, closeModel } = useDataModel()
const { loading, setLoading } = useLoading()

const openHandle = (tenantId: string) => {
  formData.value.tenantId = tenantId
  openModel('设置租户管理员', false, true, Operation.CREATE)
}

const handleCancel = () => {
  closeModel()
  formData.value = {
    tenantId: '',
    username: ''
  }
  setLoading(false)
}

const handleOk = async (done: (closed: boolean) => void) => {
  if (dataModel.submit) {
    setLoading(true);
    if (adminModalForm.value) {
      await adminModalForm.value?.validate(async (errors: undefined | Record<string, ValidatedError>) => {
        if (!errors) {
          await setUpAdmin(formData.value.tenantId, formData.value.username)
          setLoading(false)
          handleCancel()
          done(true)
        } else {
          done(false)
          setTimeout(() => {
            setLoading(false)
          }, 1500)
        }
      })
    }
  }
  done(false)
}

defineExpose({ openHandle })
</script>

<script lang="ts">
export default {
  name: 'AdminModal'
}
</script>

<style scoped>

</style>
